<template>
  <div class="layout-col flex2 bss">
    <div class="ww100 flex-bc plr12 ptb8 bs4">
      <div class="flex-sc">
        <span class="f15 fw">告警点</span>
      </div>
      <div class="flex-ec flex1 h32">
        <el-button class="bgi3 white" @click.stop="toPath('/sensor')" v-if="!isNull(publicStore.form)">返回</el-button>
        <el-button class="bgi3 white" @click.stop="asyncAlarm()">同步告警</el-button>
      </div>
    </div>
    <div class="row bgi22">
      <div :style="{textAlign: v.align, paddingRight: v.name=='操作'?'10px': 'inherit'}" v-for="(v, i) in state.content" :key="i" v-show="v.show" :class="v.width">{{v.name}}</div>
    </div>
    <div class="flex1 overlay ww100 flex-col-ss">
      <el-tree 
      class="ww100" 
      ref="treeRef" 
      :data="state.tree"
      :node-key="state.key" 
      :current-node-key="defaultId"
      :props="defaultProps"
      highlight-current    
      accordion
      @node-click="handleNodeClick"
      empty-text="暂无数据">
        <template #default="{ node, data }">
          <span class="row">
            <div v-show="v.show" :class="v.width" :style="{textAlign: v.align}" v-for="(v, i) in state.content" :key="i">
              <span v-if="typeof(v.key) == 'object'" class="i21 cursor mlr5" v-for="(vv, kk, ii) in v.key" :key="ii" :class="kk=='add'?'none':''" @click.stop="handleClick(kk, data)">{{vv}}</span>
              <span v-else-if="v.key=='*'">{{index+1}}</span>
              <span v-else>{{isNull(data[v.key]) && v.key!=''? '/' : data[v.key]}}</span>
            </div>
          </span>
        </template>
      </el-tree>
    </div>
    <Add @init="init" :state="state" ref="exposeRef" />
  </div>
</template>

<script lang="ts" setup>
  import api from '@/api'
  const route = useRoute()
	const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const state = reactive({
	  ...publicStore.$state,
    key: 'id',
    parent: 'parent_id',
    content: [
      { width: 'flex1', show: true, align: 'start', key: 'name', name: '名称' }, 
    ],
  })
  let exposeRef = $ref()
  let treeRef = $ref()
  let defaultProps = {
    children: 'children',
    label: 'name',
  }
  let defaultId = $ref()
  let expandNode = $ref('')

  onMounted(async() => {
    publicStore.form = route.query
    init()
  })

  const init = async() => {
    let query = {"o": "o_sensor", "p": [publicStore.distributId], "i": 0}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    let sensorList = proxy.isNull(res)? [] : res
    publicStore.list = sensorList
    let query2 = getQuery(sensorList)
    let params2 = {queryApi2: query2}
    let res2 = await publicStore.post(params2)
    let measureList = proxy.isNull(res2)? [] : res2
    let list = geList(sensorList, measureList)
    state.list = sensorList.concat(list)
    state.tree = proxy.treeData(state.list, state.key, state.parent, 'children')
    let node = proxy.findNode(state.tree, (node) => { return defaultId? node[state.key] == defaultId : !node.children })
    await nextTick()
    handleNodeClick(node)
  }

  const getQuery = (val) => {
    let tempArr = [] 
    val.filter(a=>a.class == 0).forEach(v => {
        let exist = tempArr.find(a=>a.p[0] == v.type)
        if(!exist) tempArr.push({"o":"o_sensor_template_measure_property","p":[v.type]})
    })
    return tempArr
  }

  const geList = (sensorList, measureList) => {
    let tempArr = [] 
    sensorList.filter(a=>a.class == 0).forEach(v => {
        let arr = measureList.filter(a=>a.sensor_type == v.type)
        if(arr){
          arr.forEach((vv, ii) => {
            delete vv.id
            let temp = Object.assign({id: v.id + '_' +vv.code + '_' + ii, parent_id: v.id}, vv)
            if(!defaultId && publicStore.form[state.key] && publicStore.form[state.key] == v[state.key]) defaultId = temp.id
            tempArr.push(temp)
          })
        }
    })
    return tempArr
  }

  const handleNodeClick = async(val) => {
    defaultId = val[state.key]
    treeRef.setCurrentKey(defaultId, true)
    publicStore.active = val
  }

  // 同步
  const asyncAlarm = async() => {
     ElMessageBox.confirm('是否确定同步到同类型设备?', '重要提示！', {
      confirmButtonText: '确定',
      cancelButtonText: '关闭',
      type: 'error'
    }).then(async() => {
      expandNode = publicStore.active.hasOwnProperty('children')? publicStore.active : proxy.findNode(state.tree, (node) => { return node[state.key] == publicStore.active.parent_id })
      let alertList = await getAlertList()
      console.log('alertList', alertList)
      let actionList = await getActionList(alertList)
      console.log('alctionList', actionList)
      let addQuery = await setQuery(alertList, actionList)
      console.log('addQuery', addQuery)
      let delQuery = await setDel(alertList, actionList)
      console.log('delQuery', delQuery)
      await onAdd(addQuery, delQuery)
    })
  }

  const onAdd = async(addQuery, delQuery) =>{
    api.updateApi(addQuery).then((res) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '同步成功', type: 'success' })
        onDel(delQuery)
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '同步失败', type: 'error' })
    })
  }

  const onDel = async(delQuery) =>{
    api.updateApi(delQuery).then((res) => {
    if(res.errcode == 0){
        ElNotification({ title: '提示', message: '清理成功', type: 'success' })
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '清理失败', type: 'error' })
    })
  }

  const getAlertList = async() => {
    let queryArrInterval = []
    let queryArrState = []
    expandNode.children.map(async item=> {
      let queryInterval = {"o": "o_sensor_alert_interval", "i": 0, "p": [expandNode.id, item.code]} 
      let queryState = {"o": "o_sensor_alert_state", "i": 0, "p": [expandNode.id, item.code]} 
      queryArrInterval.push(queryInterval)
      queryArrState.push(queryState)
    })
    let queryInterval = {"o": "o_sensor_alert_interval", "i": 1, "p": [publicStore.distributId]} 
    let queryState = {"o": "o_sensor_alert_state", "i": 1, "p": [publicStore.distributId]} 
    let params = {queryApi1: queryInterval, queryApi2: queryState, queryApi3: queryArrInterval, queryApi4: queryArrState}
    let res = await publicStore.post(params)
    return res
    // let res = await store.dispatch('D', {asyncInterval: interval, asyncState: state, asyncQuery1: queryArrInterval, asyncQuery2: queryArrState})
  }

  const getActionList = async(list) => {
    let queryArrActionInterval = []
    let queryArrActionState = []
    list.queryApi3.map(async item=> {
      let queryActionInterval = {"o": "o_sensor_alert_interval_action", "i": 1, "p": [item.id]} 
      queryArrActionInterval.push(queryActionInterval)
    })
    list.queryApi4.map(async item=> {
      let queryActionState = {"o": "o_sensor_alert_state_action", "i": 0, "p": [item.id]} 
      queryArrActionState.push(queryActionState)
    })
    let queryInterval = {"o": "o_sensor_alert_interval_action", "i": 2, "p": [publicStore.distributId]} 
    let queryState = {"o": "o_sensor_alert_state_action", "i": 1, "p": [publicStore.distributId]} 
    let params = {queryApi5: queryInterval, queryApi6: queryState, queryApi7: queryArrActionInterval, queryApi8: queryArrActionState}
    let res = await publicStore.post(params)
    return res
    // let res = await store.dispatch('D', {asyncActionInterval: interval, asyncActionState: state, asyncQuery3: queryArrActionInterval, asyncQuery4: queryArrActionState})
  }

  const setQuery = async(list, list2) => {
    let data = publicStore.list.filter(a=>a.type == expandNode.type)
    let queryArr = []
    data.forEach((item, index) => {
      if(!proxy.isNull(list.queryApi3)){
        list.queryApi3.forEach((v, i) => {
          let id = new Date().getTime() + index*100 + i
          // let alarm_code = new Date().getTime() + index*100 + i + ''
          let add = {"a": '同步', "o": 'o_sensor_alert_interval', "t": 'add', id: id, sensor_id: item.id }
          let query = Object.assign({}, v, add)
          queryArr.push(query)
          // 下级处理
          if(!proxy.isNull(list2.queryApi7)){
            list2.queryApi7.forEach((vv, ii) => { 
              if(v.id == vv.alert_id){
                let add2 = {"a": '同步', "o": 'o_sensor_alert_interval_action', "t": 'add', id: new Date().getTime() + index*100 + ii, alert_id: query.id + '', sensor_id: vv.sensor_id, sensor_ctrl_pro: vv.sensor_ctrl_proo, ctrl_code: vv.ctrl_code }
                queryArr.push(add2)
              }
            })
          } 
        })
      }
      if(!proxy.isNull(list.queryApi4)){
        list.queryApi4.forEach((v, i) => {
          let id = new Date().getTime() + index*100 + i
          // let alarm_code = new Date().getTime() + index*100 + i + ''
          let add = {"a": '同步', "o": 'o_sensor_alert_state', "t": 'add', id: id, sensor_id: item.id }
          let query = Object.assign({}, v, add)
          queryArr.push(query)
          // 下级处理
          if(!proxy.isNull(list2.queryApi8)){
            list2.queryApi8.forEach((vv, ii) => { 
              if(v.id == vv.alert_id){
                let add2 = {"a": '同步', "o": 'o_sensor_alert_state_action', "t": 'add', id: new Date().getTime() + index*100 + ii, alert_id: query.id  + '', sensor_id: vv.sensor_id, sensor_ctrl_pro: vv.sensor_ctrl_proo, ctrl_code: vv.ctrl_code }
                queryArr.push(add2)
              }
            }) 
          }
        })
      }
    })
    return queryArr
  }
  const setDel = async(list, list2) => {
    let queryArr = []
    list.queryApi1.forEach((v, i) => {
      let del = {"a": '删除', "o": 'o_sensor_alert_interval', "t": 'del', id: v.id}
      queryArr.push(del)
    })
    list.queryApi2.forEach((v, i) => {
      let del = {"a": '删除', "o": 'o_sensor_alert_state', "t": 'del', id: v.id}
      queryArr.push(del)
    })
    list2.queryApi5.forEach((v, i) => {
      let del = {"a": '删除', "o": 'o_sensor_alert_interval_action', "t": 'del', id: v.id}
      queryArr.push(del)
    })
    list2.queryApi6.forEach((v, i) => {
      let del = {"a": '删除', "o": 'o_sensor_alert_state_action', "t": 'del', id: v.id}
      queryArr.push(del)
    })
    return queryArr
  }

</script>
  
<style scoped lang="scss">

</style>
  